import Express from "express";
import router from "./routes/index.js";
import bodyParser from "body-parser";
import db from "./mongodb/db.js";
import path from "path";
import config from "config-lite";
import cookieParser from "cookie-parser";
import connectMongo from "connect-mongo";
import session from "express-session";
import history from "connect-history-api-fallback";
import chalk from "chalk";
let app = Express();

//2.0 将所有api的请求响应content-type设置为application/json
app.all('/*', (req, res, next) => {
    //设置允许跨域响应报文头
    //设置跨域
    // 启用 Node 服务器端的 cors 跨域
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "*");

    // res.setHeader('Content-Type', 'application/json;charset=utf-8');
    next();
});

app.get("/", (req, res) => {
  res.send(`欢迎来到Myelm，Node后端Api主页`);
  // res.sendFile(__dirname + "/public/img/default.jpg");
});

// 配置解析表单 POST 请求体插件 （注意：一定要在 app.use(router) 之前）
// parse application/x-www-form-urlencoded 解析application
app.use(
  bodyParser.urlencoded({
    extended: false
  })
);
// parse application/json 解析
app.use(bodyParser.json());

const MongoStore = connectMongo(session);
app.use(cookieParser());
app.use(
  session({
    name: config.session.name,
    secret: config.session.secret,
    resave: true,
    saveUninitialized: false,
    cookie: config.session.cookie,
    store: new MongoStore({
      url: config.url
    })
  })
);

router(app);
app.use(history());
app.use(Express.static("./public")),
  {
    // setHeaders: function (res, path, stat) {
    //     if (res && path.indexOf("/public/img") > -1) {
    //         res.setHeader("Content-type", "img; charset=base64");
    //     }
    // }
  };
app.listen(config.port, () => {
  console.log(chalk.yellow("成功监听到端口" + config.port));
});
